/**
 * Copyright (c) 2006-2016 Huize Ltd. All Rights Reserved. 
 *  
 * This code is the confidential and proprietary information of   
 * Hzins. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with Huize,http://www.huize.com.
 *  
 */
package com.agan.concurrent.lock;

import java.util.Calendar;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {

    private ReentrantLock lock = null;

    public int data = 100; // 用于线程同步访问的共享数据

    public TestLock() {
	lock = new ReentrantLock(); // 创建一个自由竞争的可重入锁
    }

    public ReentrantLock getLock() {
	return lock;
    }

    public void testReentry() {
	lock.lock();
	try {
	    Thread.sleep(1000 * 10);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
	Calendar now = Calendar.getInstance();
	System.out.println(now.getTime() + " " + Thread.currentThread() + " get lock.");
    }

    public static void main(String[] args) {
	TestLock tester = new TestLock();

	// 1、测试可重入
	tester.testReentry();
	tester.testReentry(); // 能执行到这里而不阻塞，表示锁可重入
	tester.testReentry(); // 再次重入
	System.out.println("释放.............");
	// 释放重入测试的锁，要按重入的数量解锁，否则其他线程无法获取该锁。
	tester.getLock().unlock();
	tester.getLock().unlock();
	tester.getLock().unlock();
    }

}